/*
 * @Author: zs.duan
 * @Date: 2024-09-21 18:08:44
 */
var express = require("express");
var router = express.Router();
const Db = require("../../utils/db");
const createSqlv2 = require("../../utils/createsql-v2.0.0.js");
const path = require('path');
const { errorCode, successCode, config } = require('../../config/config');
const utils = require('../../utils/utils.js');
const objectCheck = require("./adminApiCheck.js");
const nodeExcel = require('excel-export'); //处理 excel
const schedule = require('../../utils/schedule.js');
/**
 * @swagger
 * /api/v2/admin/getMenu:
 *    get:
 *      tags:
 *      - 后台管理 菜单管理
 *      summary: 查询菜单返回tree
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: name
 *          description: 英文名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 中文名称
 *          in: query
 *          required: false
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getMenu", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;

    let { pageSize, page, path, name, title } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('admin_new_menu.* , user_admin.user_name as username').from("admin_new_menu")
        .leftJoin("user_admin")
        .on('admin_new_menu.create_user = user_admin.ID')
        .where(` ${path ? "path like '%" + path + "%' " : ''}`)
        .and(`${name ? "name like '%" + name + "%'" : ''} `)
        .and(`${title ? "title like '%" + title + "%'" : ''}`)
        .and(`admin_new_menu.is_del = 0`)
        .build();

    let data = await Db.query(sql, res);
    if (data.code) return;
    data = utils.deleteArrayObject(data, ["is_del"]);
    data = utils.formatDateByArray(data, ["createdtime", "updatetime"]);
    data = utils.formatNumberToBoolean(data, ["hidden", "is_keep_alive", "affix", "is_show"]);
    if (name || title) {
        return res.json({
            ...successCode[200],
            data: {
                data: data,
                count: 0
            }
        })
    }
    let ParentMenu = [];
    data.forEach(item => {
        if (item.type == 1) {
            ParentMenu.push({
                ...item,
                children: []
            })
        }
    });
    data.forEach(item => {
        let parent = ParentMenu.filter(parentItem => parentItem.ID == item.parent_ID);
        if (parent.length) {
            parent[0].children.push(item);
            parent[0].children.sort((a, b) => a.sorts - b.sorts)
        }
    });
    ParentMenu.sort((a, b) => a.sorts - b.sorts);

    return res.json({
        ...successCode[200],
        data: {
            data: ParentMenu,
            count: 0
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/getParentMenu:
 *    get:
 *      tags:
 *      - 后台管理 菜单管理
 *      summary: 查询父级菜单
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getParentMenu", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let sql = createSqlv2().select("ID, title").from("admin_new_menu").where(`type = 1`).build();
    let data = await Db.query(sql, res);
    if (data.code < 0) return;
    let sendData = data.map(item => {
        return {
            value: item.ID,
            label: item.title
        }
    })
    return res.json({
        ...successCode[200],
        data: sendData
    })
})


/**
 * @swagger
 * /api/v2/admin/addAdminNewMenu:
 *    post:
 *      tags:
 *      - 后台管理 菜单管理 
 *      summary: 菜单管理新增
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                parent_ID:
 *                  type: string
 *                  description: 父级路由ID
 *                name:
 *                  type: string
 *                  description: 菜单name
 *                type:
 *                  type: number
 *                  description: 菜单类型 1 目录 2 菜单 3外部连接
 *                path:
 *                  type: string
 *                  description: 路由路径
 *                redirect:
 *                  type: string
 *                  description: 重定向地址
 *                component:
 *                  type: string
 *                  description: 组件路径
 *                hidden:
 *                  type: boolean
 *                  description: 是否隐藏
 *                is_keep_alive:
 *                  type: boolean
 *                  description: 是否保持
 *                icon:
 *                  type: string
 *                  description: 图标
 *                title:
 *                  type: string
 *                  description: 菜单名称
 *                affix:
 *                  type: string
 *                  description: 是否固定
 *                meta:
 *                  type: string
 *                  description: 更多mata配置
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: boolean
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addAdminNewMenu", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.AdminNewMenu_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.createdtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = "";
    sql = createSqlv2().insert("admin_new_menu").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updateAdminNewMenu:
 *    post:
 *      tags:
 *      - 后台管理 菜单管理 
 *      summary: 菜单管理 更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 编辑ID
 *                parent_ID:
 *                  type: string
 *                  description: 父级路由ID
 *                name:
 *                  type: string
 *                  description: 菜单name
 *                type:
 *                  type: number
 *                  description: 菜单类型 1 目录 2 菜单 3外部连接
 *                path:
 *                  type: string
 *                  description: 路由路径
 *                redirect:
 *                  type: string
 *                  description: 重定向地址
 *                component:
 *                  type: string
 *                  description: 组件路径
 *                hidden:
 *                  type: boolean
 *                  description: 是否隐藏
 *                is_keep_alive:
 *                  type: boolean
 *                  description: 是否保持
 *                icon:
 *                  type: string
 *                  description: 图标
 *                title:
 *                  type: string
 *                  description: 菜单名称
 *                affix:
 *                  type: string
 *                  description: 是否固定
 *                meta:
 *                  type: string
 *                  description: 更多mata配置
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: boolean
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateAdminNewMenu", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID, is_show, name } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let data = {};
    let sql = "";
    if (is_show == true && !name) {
        sql = createSqlv2().update("admin_new_menu").set({ is_show: is_show }).where(`ID = '${ID}'`).build();
    } else {
        data = utils.checkData(req.body, objectCheck.AdminNewMenu_add);
        if (data.code > 200) return res.json(data)
        data = data.data;
        data.create_user = isLogin.data.ID;
        data.updatetime = utils.getTime();
        sql = createSqlv2().update("admin_new_menu").set(data).where(`ID = '${ID}'`).build();
    }
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});

/**
 * @swagger
 * /api/v2/admin/deleteAdminNewMenu:
 *    post:
 *      tags:
 *      - 后台管理 菜单管理 
 *      summary: 菜单管理 删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 编辑ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/deleteAdminNewMenu", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().select().from("admin_new_menu").where(`ID = '${ID}'`).build();
    let data = await Db.query(sql, res);
    if (data.code) return;
    if (!data.length) {
        return res.json({
            ...errorCode[10008],
            message: "没有找到该数据"
        })
    }
    data = {
        updatetime: utils.getTime(),
        create_user: isLogin.data.ID,
        is_del: 1
    }
    sql = createSqlv2().update("admin_new_menu").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getAdminNewRoles:
 *    get:
 *      tags:
 *      - 后台管理 权限管理
 *      summary: 查询权限
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: name
 *          description: 权限名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          description: 页码
 *          in: query
 *          required: false
 *          type: number
 *          default: 1
 *        - name: pageSize
 *          description: 条数
 *          in: query
 *          required: false
 *          type: number
 *          default: 10
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getAdminNewRoles", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;

    let { pageSize, page, name } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('admin_new_roles.* , user_admin.user_name as username').from("admin_new_roles")
        .leftJoin("user_admin")
        .on('admin_new_roles.create_user = user_admin.ID')
        .where(` ${name ? "name like '%" + name + "%' and " : ''} admin_new_roles.is_del = 0`)
        .limit(`${pageSize * (page - 1)}, ${pageSize}`)
        .build();
    let countSql = createSqlv2().select("count(*) as count").from("admin_new_roles")
        .where(` ${name ? "name like '%" + name + "%' and " : ''} admin_new_roles.is_del = 0`)
        .build();

    let data = await Db.query(sql, res);
    if (data.code) return;
    let countData = await Db.query(countSql);
    if (countData.code) return;
    data = utils.deleteArrayObject(data, ["is_del"]);
    data = utils.formatDateByArray(data, ["createdtime", "updatetime"]);
    return res.json({
        ...successCode[200],
        data: {
            data: data,
            count: countData[0].count
        }
    })
})


/**
 * @swagger
 * /api/v2/admin/addAdminNewRoles:
 *    post:
 *      tags:
 *      - 后台管理 权限管理 
 *      summary: 权限管理新增
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                name:
 *                  type: string
 *                  description: 权限名称
 *                code:
 *                  type: number
 *                  description: code
 *                remark:
 *                  type: string
 *                  description: 备注
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addAdminNewRoles", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.AdminNewRoles_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.createdtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = "";
    if (data.is_show == 1) {
        sql = createSqlv2().update("admin_new_roles").set("is_show = 0").where("is_show = 1").build();
        await Db.query(sql, res);
    }
    sql = createSqlv2().insert("admin_new_roles").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updateAdminNewRoles:
 *    post:
 *      tags:
 *      - 后台管理 权限管理 
 *      summary: 权限管理更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                name:
 *                  type: string
 *                  description: 权限名称
 *                code:
 *                  type: number
 *                  description: code
 *                remark:
 *                  type: string
 *                  description: 备注
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateAdminNewRoles", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let data = {};
    let sql = "";
    data = utils.checkData(req.body, objectCheck.AdminNewRoles_add);
    if (data.code > 200) return res.json(data)
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.updatetime = utils.getTime();
    sql = createSqlv2().update("admin_new_roles").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});

/**
 * @swagger
 * /api/v2/admin/deleteAdminNewRoles:
 *    post:
 *      tags:
 *      - 后台管理 权限管理 
 *      summary: 权限管理删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/deleteAdminNewRoles", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().select().from("admin_new_roles").where(`ID = '${ID}'`).build();
    let data = await Db.query(sql, res);
    if (data.code) return;
    if (!data.length) {
        return res.json({
            ...errorCode[10008],
            message: "没有找到该数据"
        })
    }
    data = {
        updatetime: utils.getTime(),
        create_user: isLogin.data.ID,
        is_del: 1
    }
    sql = createSqlv2().update("admin_new_roles").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getMenuAndActionsByRolesIdFromEdit:
 *    get:
 *      tags:
 *      - 后台管理 权限管理
 *      summary: 根据角色ID获取菜单和操作列表 编辑
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          description: 权限ID
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getMenuAndActionsByRolesIdFromEdit", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.query;
    if (!ID) {
        return res.json(errorCode[10003])
    }
    // 查询所有菜单
    let sql = "";
    sql = createSqlv2().select().from("admin_new_menu").where(`is_del = 0`).build();
    let menuData = await Db.query(sql, res);
    if (menuData.code) return;
    let actions = [
        { label: '主页面', value: "page" },
        { label: "新增", value: "add" },
        { label: "编辑", value: "edit" },
        { label: "删除", value: "delete" },
        { label: "详情", value: "view" },
        { label: "导出", value: "export" },
        { label: "导入", value: "import" }
    ]
    let ParentMenu = [];
    menuData.forEach(item => { if (item.type == 1) ParentMenu.push(item); });
    ParentMenu.sort((a, b) => { return a.sorts - b.sorts });
    let menus = []
    ParentMenu.forEach(item => {
        menus.push(item);
        let children = []
        menuData.forEach(menuItem => {
            if (item.ID == menuItem.parent_ID) children.push(menuItem)
        });
        children.sort((a, b) => { return a.sorts - b.sorts });
        menus.push(...children);
    });
    let pages = [];
    menus.forEach(item => {
        if (item.type == 2) {
            pages.push({ label: item.title, value: item.ID, actions: actions, roles: [] })
        } else {
            pages.push({ label: item.title, value: item.ID, actions: [actions[0]], roles: [] })
        }
    })

    // 查询所有操作
    sql = createSqlv2().select().from("admin_menu_by_roles").where("role_ID", "=", `'${ID}'`).build();
    let roles = await Db.query(sql);
    if (roles.code) return;
    roles.forEach(item => {
        let index = pages.findIndex(i => i.value == item.menu_ID);
        if (index != -1 && item.actions) {
            pages[index].roles = item.actions.split(",")
        }
    });
    return res.json({
        ...successCode[200],
        data: {
            data: pages,
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/updateMenuAndActions:
 *    post:
 *      tags:
 *      - 后台管理 权限管理 
 *      summary: 权限新增
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                rolesID:
 *                  type: string
 *                  description: 权限id
 *                pages:
 *                  type: Array
 *                  description: 页面列表
 *                  items:
 *                    pageID:
 *                      type: string
 *                      description: 页面id
 *                    actions:
 *                      type: Array
 *                      description: 页面操作列表
 *                      items:
 *                        actionType: 
 *                          type: string
 *                          description: 操作类型 page / add / edit / delete / view / export / import
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateMenuAndActions", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { rolesID, pages } = req.body;
    if (!pages || !rolesID) {
        return res.json(errorCode[10003])
    }
    let sql = '';
    sql = createSqlv2().delete("admin_menu_by_roles").where(`role_ID = '${rolesID}'`).build();
    await Db.query(sql, res);
    let updatePages = [];
    pages.forEach(item => {
        updatePages.push({
            ID: utils.getUuid(),
            role_ID: rolesID,
            menu_ID: item.pageID,
            actions: item.actions.join(","),
            create_user: isLogin.data.ID,
            createdtime: utils.getTime()
        })
    })
    sql = createSqlv2().insert("admin_menu_by_roles").values(updatePages).build();
    await Db.query(sql, res);
    return res.json({
        ...successCode[200]
    })
});


/**
 * @swagger
 * /api/v2/admin/getMenuAndActions:
 *    get:
 *      tags:
 *      - 后台管理 权限管理
 *      summary: 获取权限列表
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getMenuAndActions", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let sql = "";
    /**查询所有菜单 开始*/
    sql = createSqlv2().select().from("admin_new_menu").where(`is_del = 0`).build();
    let menus = await Db.query(sql, res);
    if (menus.code) return;
    menus = utils.formatDateByArray(menus, ["createdtime", "updatetime"]);
    menus = utils.deleteArrayObject(menus, ['is_del', 'is_show', 'create_user']);
    menus = utils.formatNumberToBoolean(menus, ['affix', 'hidden', 'is_keep_alive']);
    /**查询所有菜单 结束*/

    /**查询用户信息 开始*/
    sql = createSqlv2().select().from("user_admin").where(`ID = '${isLogin.data.ID}'`).build();
    let userInfo = await Db.query(sql, res);
    if (userInfo.code) return;
    /**查询用户信息 结束*/

    /**查询权限信息 开始*/
    const { role_ID, isSuperAdmin } = userInfo[0];
    sql = createSqlv2().select().from("admin_menu_by_roles").where(`role_ID = '${role_ID}'`).build();
    let roles = [];
    if (!isSuperAdmin) {
        roles = await Db.query(sql, res)
        if (roles.code) return;
    } else {
        menus.forEach(item => {
            roles.push({
                menu_ID: item.ID,
                actions: item.type == 2 ? "page,add,edit,delete,view,export,import" : "page"
            })
        })
    }
    /**查询权限信息 结束*/

    let menuActions = [];
    let newMenu = [];
    roles.forEach((item, index) => {
        let idx = menus.findIndex(i => i.ID == item.menu_ID);
        let meta = {};
        try {
            meta = JSON.parse(item.meta);
        } catch (error) {
            meta = {}
        }
        newMenu.push({
            ...menus[idx],
            meta: {
                ...meta,
                title: menus[idx].title,
                affix: menus[idx].affix,
                icon: menus[idx].icon,
                is_keep_alive: menus[idx].is_keep_alive,
                roles: []
            }
        })
        if (index != -1 && item.actions && item.actions.includes("page")) {
            newMenu[index].meta = {
                ...newMenu[index].meta,
                roles: item.actions.split(",")
            }
        }
    });
    newMenu = utils.deleteArrayObject(newMenu, ['title', 'affix', 'hidden', 'is_keep_alive'])
    menuActions = newMenu.filter(item => item.type == 1 && item.meta.roles && item.meta.roles.length);
    menuActions.forEach(item => {
        let children = newMenu.filter(i => i.parent_ID == item.ID && i.meta.roles && i.meta.roles.length);
        children.sort((a, b) => { return a.sorts - b.sorts });
        item.children = children;
    });
    menuActions.sort((a, b) => { return a.sorts - b.sorts });
    return res.json({
        ...successCode[200],
        data: {
            data: menuActions,
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/getAllRoles:
 *    get:
 *      tags:
 *      - 后台管理 权限管理
 *      summary: 获取权限所以列表
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getAllRoles", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let sql = createSqlv2().select().from("admin_new_roles").where(`is_del = 0`).build();
    let result = await Db.query(sql, res);
    let data = [];
    result.forEach(item => {
        data.push({
            value: item.ID,
            label: item.name,
        })
    })
    return res.json({
        ...successCode[200],
        data: {
            data: data
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/getAdminUser:
 *    get:
 *      tags:
 *      - 后台管理 后台用户管理
 *      summary: 查询用户
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: username
 *          description: 用户名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          description: 页码
 *          in: query
 *          required: false
 *          type: number
 *          default: 1
 *        - name: pageSize
 *          description: 条数
 *          in: query
 *          required: false
 *          type: number
 *          default: 10
 *        - name: isAll
 *          description: 是否查询全部
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getAdminUser", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { username, page, pageSize, isAll } = req.query;
    if (isAll) {
        let sql = createSqlv2().select('ID AS value,user_name as label')
            .from("user_admin")
            .where('user_admin.is_del = 0').build();
        let result = await Db.query(sql, res);
        if (result.code) return;
        return res.json({
            ...successCode[200],
            data: {
                data: result
            }
        })
    }
    page = page - 1 || 0;
    pageSize = pageSize || 10;
    let sql = createSqlv2().select('user_admin.*,admin_new_roles.name as roleName')
        .from("user_admin")
        .leftJoin('admin_new_roles')
        .on('user_admin.role_ID = admin_new_roles.ID')
        .where(`user_admin.user_name like '%${username ? username : ''}%'`)
        .and('user_admin.is_del = 0')
        .order('user_admin.addtime desc')
        .limit(page * pageSize, pageSize)
        .build();
    let sqlTotal = createSqlv2().select('count(*) as num').from("user_admin")
        .where(`user_admin.user_name like '%${username ? username : ''}%'`)
        .and('user_admin.is_del = 0')
        .build();
    let result = await Db.query(sql, res);
    let total = await Db.query(sqlTotal, res);
    if (result.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime", 'lastLoginTime']);
    result = utils.deleteArrayObject(result, ['is_not_edit', 'password', 'token']);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: total[0].num
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/updateAdminUser:
 *    post:
 *      tags:
 *      - 后台管理 后台用户管理 
 *      summary: 更新后台用户信息
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                user_name:
 *                  type: Array
 *                  description: 用户名
 *                email:
 *                  type: Array
 *                  description: 用户邮箱
 *                role_ID:
 *                  type: Array
 *                  description: 权限id
 *                is_del:
 *                  type: Array
 *                  description: 是否删除
 *                password:
 *                  type: Array
 *                  description: 初始化密码
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateAdminUser", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID, user_name, email, role_ID, is_disable, password } = req.body;
    if (!ID) res.json(errorCode[10003]);
    let updateData = {
        updatetime: utils.getTime()
    };
    if (user_name) updateData.user_name = user_name;
    if (email) updateData.email = email;
    if (role_ID) updateData.role_ID = role_ID;
    if (is_disable != undefined) updateData.is_disable = is_disable == 1 ? 1 : 0;
    if (password) updateData.password = utils.MD5(password);
    let sql = createSqlv2().update("user_admin").set(updateData).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/addAdminUser:
 *    post:
 *      tags:
 *      - 后台管理 后台用户管理 
 *      summary: 添加后台用户
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                user_name:
 *                  type: Array
 *                  description: 用户名
 *                email:
 *                  type: Array
 *                  description: 用户邮箱
 *                role_ID:
 *                  type: Array
 *                  description: 权限id
 *                is_del:
 *                  type: Array
 *                  description: 是否删除
 *                password:
 *                  type: Array
 *                  description: 初始化密码
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addAdminUser", async function (req, res) {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.adminUser_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    data.password = data.password ? utils.MD5(data.password) : utils.MD5('123456');
    data.is_del = 0;
    let sql = createSqlv2().insert("user_admin").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/delAdminUser:
 *    post:
 *      tags:
 *      - 后台管理 后台用户
 *      summary: 后台用户-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delAdminUser", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({ ...errorCode[10003] })
    }
    let sql = createSqlv2().select().from("user_admin").where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code > 200) return res.json(result);
    if (result[0].is_not_edit != 0) {
        return res.json({ ...errorCode[401] })
    }
    sql = createSqlv2().update("user_admin").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getLog:
 *    get:
 *      tags:
 *      - 后台管理 日志管理
 *      summary: 日志管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: requestUrl
 *          description: 请求地址
 *          in: query
 *          required: false
 *          type: string
 *        - name: ip
 *          description: 请求地址
 *          in: query
 *          required: false
 *          type: string
 *        - name: username
 *          description: 操作人
 *          in: query
 *          required: false
 *          type: string
 *        - name: startTime
 *          description: 请求地址
 *          in: query
 *          required: false
 *          type: string
 *        - name: endTime
 *          description: 请求地址
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getLog", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, requestUrl, ip, username, startTime, endTime } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select()
        .from('actionlog')
        .where(requestUrl ? `requestUrl LIKE '%${requestUrl}%'` : '')
        .and(username ? `username LIKE '%${username}%'` : '')
        .and(ip ? `ip LIKE '%${ip}%'` : '')
        .and(startTime ? `createdTime >= '${startTime}'` : '')
        .and(endTime ? `createdTime <= '${endTime}'` : '')
        .order("createdTime DESC")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`)
        .build();
    let countSql = createSqlv2().select('count(*) as count')
        .from('actionlog')
        .where(requestUrl ? `requestUrl LIKE '%${requestUrl}%'` : '')
        .and(username ? `username LIKE '%${username}%'` : '')
        .and(ip ? `ip LIKE '%${ip}%'` : '')
        .and(startTime ? `createdTime >= '${startTime}'` : '')
        .and(endTime ? `createdTime <= '${endTime}'` : '')
        .build();
    let result = await Db.query(sql, res);
    let count = await Db.query(countSql, res);
    if (result.code || count.code) return;
    result = utils.formatDateByArray(result, ["createdTime"])
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: count[0].count
        },
    })
})

/**
 * @swagger
 * /api/v2/admin/clearLog:
 *    post:
 *      tags:
 *      - 后台管理 日志管理
 *      summary: 日志管理-清空
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.post("/clearLog", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let sql = createSqlv2().customAll("TRUNCATE TABLE actionlog").build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getUser:
 *    get:
 *      tags:
 *      - 后台管理 普通用户
 *      summary: 普通用户-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: username
 *          description: 用户名
 *          in: query
 *          required: false
 *          type: string
 *        - name: email
 *          description: 邮箱
 *          in: query
 *          required: false
 *          type: string
 *        - name: tel
 *          description: 手机号
 *          in: query
 *          required: false
 *          type: string
 *        - name: admin_user_id
 *          description: 管理员ID
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */

router.get("/getUser", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;

    let { pageSize, page, username, email, tel, admin_user_id } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let where = createSqlv2().from('web_userinfo')
        .leftJoin('user_admin').on('web_userinfo.createByUser', '=', 'user_admin.ID')
        .where(`web_userinfo.is_del != 1`)
        .and(username ? `web_userinfo.username LIKE '%${username}%'` : '')
        .and(email ? `web_userinfo.email LIKE '%${email}%'` : '')
        .and(tel ? `web_userinfo.tel LIKE '%${tel}%'` : '')
        .and(admin_user_id ? `web_userinfo.admin_user_id = '${admin_user_id}'` : '')
        .order('web_userinfo.addtime desc')
        .build();
    let sql = createSqlv2().select(`web_userinfo.* , user_admin.user_name as createByUser`).custom(where).build();
    let conutSql = createSqlv2().select('count(*) as count').custom(where).build();
    let result = await Db.query(sql, res);
    let count = await Db.query(conutSql, res);
    if (result.code || count.code) return;

    result.forEach(item => {
        item.addtime = item.addtime ? utils.getTime(item.addtime) : null;
        item.updatetime = item.updatetime ? utils.getTime(item.updatetime) : null;
        if (item.icon) {
            let imgUrlArr = item.icon.split("/");
            let pathArr = imgUrlArr.filter(item => { return item == "https:" || item == "http:" });
            if (!pathArr.length) {
                item.icon = config.httpImgUrl + item.icon;
            }
        }
        item.types = item.openid ? '微信小程序' : '网页端'
    })
    result = utils.formatDateByArray(result, ["addtime", "updatetime", 'lastLoginTime']);
    result = utils.deleteArrayObject(result, ['password', 'is_del', 'token', 'is_del'])
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: count[0].count
        },
    })
})

/**
 * @swagger
 * /api/v2/admin/addUser:
 *    post:
 *      tags:
 *      - 后台管理 普通用户
 *      summary:  普通用户-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                  description: 用户名
 *                  required: true
 *                password:
 *                  type: string
 *                  description: 密码
 *                icon:
 *                  type: string
 *                  description: 头像
 *                email:
 *                  type: string
 *                  description: 邮箱
 *                  required: true
 *                tel:
 *                  type: number
 *                  description: 手机号
 *                is_stop:
 *                  type: number
 *                  description: 是否禁用
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addUser", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.web_user_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    let sql = "";
    if (data.email && data.email != '') {
        sql = createSqlv2().select('ID').from('web_userinfo').where({
            email: data.email,
            is_del: 0
        }).build();
    }
    if (data.tel && data.tel != '') {
        sql = createSqlv2().select('ID').from('web_userinfo').where({
            tel: data.tel,
            is_del: 0
        }).build();
    }
    if (data.email && data.email != '' && data.tel && data.tel != '') {
        sql = createSqlv2().select('ID').from('web_userinfo')
            .where({ tel: data.tel, is_del: 0 })
            .or({ email: data.email })
            .build();
    }
    if (sql) {
        let result = await Db.query(sql, res);
        if (result.length > 0) {
            return res.json({
                code: 400,
                msg: "用户名或邮箱已存在"
            });
        }
    }
    if (!data.types) {
        data.types = 1;
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.password = data.password ? utils.MD5(data.password) : utils.MD5("123456");
    sql = createSqlv2().insert("web_userinfo").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
        data: {
            ID: data.ID
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/updateUser:
 *    post:
 *      tags:
 *      - 后台管理 普通用户
 *      summary:  普通用户-更新与重置密码
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                username:
 *                  type: string
 *                  description: 用户名
 *                  required: true
 *                password:
 *                  type: string
 *                  description: 密码
 *                icon:
 *                  type: string
 *                  description: 头像
 *                email:
 *                  type: string
 *                  description: 邮箱
 *                  required: true
 *                types:
 *                  type: string
 *                  description: 用户类型
 *                tel:
 *                  type: number
 *                  description: 手机号
 *                openid:
 *                  type: number
 *                  description: 微信openid
 *                admin_user_id:
 *                  type: string
 *                  description: 管理员ID
 *                is_stop:
 *                  type: number
 *                  description: 是否禁用
 *                reset:
 *                  type: boolean
 *                  description: 是否重置密码
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateUser", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID, username } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (username) {
        data = utils.checkData(req.body, objectCheck.web_user_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
        // 邮箱 电话不能重复
        let sql = "";
        if (data.email) {
            sql = createSqlv2().select('ID').from('web_userinfo').where(`ID != '${ID}'`)
                .and('is_del = 0')
                .and('email', `'${data.email}'`)
                .build();
        }
        if (data.tel) {
            sql = createSqlv2().select('ID').from('web_userinfo').where(`ID != '${ID}'`)
                .and('tel', `'${data.tel}'`)
                .and('is_del = 0')
                .build();
        }
        if (data.email && data.tel) {
            sql = createSqlv2().select('ID').from('web_userinfo').where(`ID != '${ID}'`)
                .and('( email', `'${data.email}'`)
                .and('is_del = 0')
                .or(`tel = '${data.tel}' )`)
                .build();
        }
        if (sql) {
            let result = await Db.query(sql, res);
            if (result.length > 0) return res.json({
                ...errorCode[10002],
                message: '邮箱或电话已存在'
            });
        }
    } else {
        data = req.body;
    }
    if (data.reset) {
        data.password = utils.MD5({ word: "123456" });
        delete data.reset;
    }

    data.updatetime = utils.getTime();
    if (data.icon) {
        data.icon = data.icon.replace(config.httpImgUrl, "");
    }
    let sql = createSqlv2().update("web_userinfo").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delUser:
 *    post:
 *      tags:
 *      - 后台管理 普通用户
 *      summary: 普通用户-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delUser", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("web_userinfo").set({ is_del: 1, updatetime: utils.getTime() }).where('ID', `'${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getLable:
 *    get:
 *      tags:
 *      - 后台管理 我的标签
 *      summary: 我的标签-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 标签内容
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getLable", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select("my_label.ID, my_label.title, my_label.addtime, my_label.updatetime , user_admin.user_name as createByUser")
        .from("my_label")
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_label.createByUser`)
        .where(`my_label.is_del != 1`)
        .and(`${title ? `my_label.title like '%${title}%'` : ''}`)
        .order("my_label.addtime desc")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`)
        .build();
    let countSql = createSqlv2().select("count(*) as count").from("my_label").where(`is_del != 1`)
        .and(`${title ? `title like '%${title}%'` : ''}`)
        .build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    if (countResult.code) return;
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addLable:
 *    post:
 *      tags:
 *      - 后台管理 我的标签
 *      summary: 我的标签-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addLable", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.label_add);
    if (data.code > 200) {
        return res.json(data)
    }
    data = data.data;
    let sql = createSqlv2().select().from("my_label").where(`title = '${data.title}' AND is_del != 1`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    if (result.length) {
        return res.json({
            ...errorCode[10002],
            message: '关键词已存在'
        })
    }
    let red = Math.floor(Math.random() * (255 - 0));
    let green = Math.floor(Math.random() * (255 - 0));
    let blue = Math.floor(Math.random() * (255 - 0));
    let color = `${red}, ${green}, ${blue}, 0.5`;
    data.color = color;
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    sql = createSqlv2().insert("my_label").value(data).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updateLable:
 *    post:
 *      tags:
 *      - 后台管理 我的标签
 *      summary: 我的标签-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateLable", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003],
        })
    }
    let data = utils.checkData(req.body, objectCheck.label_add);
    if (data.code > 200) {
        return res.json(data)
    }
    data = data.data;

    let sql = createSqlv2().select().from("my_label")
        .where(`title = '${data.title}'`)
        .and('is_del != 1')
        .and(`ID != '${ID}'`)
        .build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    if (result.length) {
        return res.json({
            ...errorCode[10002],
            message: '关键词已存在'
        })
    }
    data.updatetime = utils.getTime();
    sql = createSqlv2().update("my_label").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delLable:
 *    post:
 *      tags:
 *      - 后台管理 我的标签
 *      summary: 我的标签-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delLable", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().update("my_label").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getShowUserInfo:
 *    get:
 *      tags:
 *      - 后台管理 个人信息
 *      summary: 个人展示信息-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: username
 *          description: 用户名
 *          in: query
 *          required: false
 *          type: string
 *        - name: brief
 *          description: 简介
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getShowUserInfo", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, username, brief } = req.query;
    pageSize = pageSize || 10;
    page = page || 10;

    let sql = createSqlv2().select('my_userinfo.* , user_admin.user_name as createByUser')
        .from("my_userinfo")
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_userinfo.createByUser`)
        .where("my_userinfo.is_del != 1")
        .and(username ? `my_userinfo.username LIKE '%${username}%'` : "")
        .and(brief ? `my_userinfo.brief LIKE '%${brief}%'` : "")
        .order("my_userinfo.addtime DESC").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select("count(*) as count").from("my_userinfo")
        .where("is_del != 1")
        .and(username ? `username LIKE '%${username}%'` : "")
        .and(brief ? `brief LIKE '%${brief}%'` : "").build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    let countData = await Db.query(conutSql);
    if (countData.code) return;
    result = utils.deleteArrayObject(result, ["is_del"]);
    result = utils.formatDateByArray(result, ["addtime", 'updatetime']);
    result.forEach(v => {
        if (v.usericon && v.usericon.indexOf("http") == -1) {
            v.usericon = config.httpImgUrl + v.usericon;
        }
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countData[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addShowUserInfo:
 *    post:
 *      tags:
 *      - 后台管理 个人信息
 *      summary: 个人展示信息-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                username:
 *                  type: string
 *                  description: 用户名
 *                  required: true
 *                usericon:
 *                  type: string
 *                  description: 用户头像
 *                  required: true
 *                brief:
 *                  type: string
 *                  description: 简介
 *                work_years:
 *                  type: string
 *                  description: 工作年限
 *                tel:
 *                  type: string
 *                  description: 电话
 *                email:
 *                  type: string
 *                  description: 邮箱
 *                address:
 *                  type: string
 *                  description: 地址
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addShowUserInfo", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.userInfo_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = "";
    if (data.is_show == 1) {
        sql = createSqlv2().update("my_userinfo").set("is_show = 0").where("is_show = 1").build();
        await Db.query(sql, res);
    }
    if (data.usericon) {
        data.usericon = data.usericon.replace(config.httpImgUrl, "");
    }
    sql = createSqlv2().insert("my_userinfo").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});

/**
 * @swagger
 * /api/v2/admin/updateShowUserInfo:
 *    post:
 *      tags:
 *      - 后台管理 个人信息
 *      summary: 个人展示信息-修改
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                username:
 *                  type: string
 *                  description: 用户名 只有is_show这个参数的时候可以不传
 *                usericon:
 *                  type: string
 *                  description: 用户头像 只有is_show这个参数的时候可以不传
 *                brief:
 *                  type: string
 *                  description: 简介
 *                work_years:
 *                  type: string
 *                  description: 工作年限
 *                tel:
 *                  type: string
 *                  description: 电话
 *                email:
 *                  type: string
 *                  description: 邮箱
 *                address:
 *                  type: string
 *                  description: 地址
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/updateShowUserInfo", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID, is_show, username } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (username) {
        data = utils.checkData(req.body, objectCheck.userInfo_add);
        data = data.data;
    } else {
        data = req.body;
    }
    if (is_show == 1) {
        let sql = createSqlv2().update("my_userinfo").set("is_show = 0").where("is_show = 1").build();
        await Db.query(sql, res);
    }
    data.updatetime = utils.getTime();
    let sql = createSqlv2().update("my_userinfo").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});


/**
 * @swagger
 * /api/v2/admin/delShowUserInfo:
 *    post:
 *      tags:
 *      - 后台管理 个人信息
 *      summary: 个人展示信息-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/delShowUserInfo", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {}
    data.updatetime = utils.getTime();
    data.is_del = 1;
    let sql = createSqlv2().update("my_userinfo").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getBlogTiltleBrfie:
 *    get:
 *      tags:
 *      - 后台管理 博客标题和简介
 *      summary: 博客标题和简介-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 标题
 *          in: query
 *          required: false
 *          type: string
 *        - name: brfie
 *          description: 简介
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */

router.get("/getBlogTiltleBrfie", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title, brfie } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('blog_title_brfie.* , user_admin.user_name as createByUser').from('blog_title_brfie')
        .leftJoin("user_admin")
        .on(`user_admin.ID = blog_title_brfie.createByUser`)
        .where('blog_title_brfie.is_del = 0')
        .and(title ? `blog_title_brfie.title like '%${title}%'` : '')
        .and(brfie ? `blog_title_brfie.brfie like '%${brfie}%'` : '')
        .order("blog_title_brfie.addtime DESC")
        .limit(`${pageSize * (page - 1)} , ${pageSize}`)
        .build();
    let sqlCount = createSqlv2().select("count(*) as count").from('blog_title_brfie')
        .where('blog_title_brfie.is_del = 0')
        .and(title ? `blog_title_brfie.title like '%${title}%'` : '')
        .and(brfie ? `blog_title_brfie.brfie like '%${brfie}%'` : '')
        .build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    let count = await Db.query(sqlCount, res);
    if (count.code) return;
    result = utils.deleteArrayObject(result, ["is_del"]);
    result = utils.formatDateByArray(result, ["addtime", 'updatetime']);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: count[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addBlogTiltleBrfie:
 *    post:
 *      tags:
 *      - 后台管理 博客标题和简介
 *      summary: 博客标题和简介-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                brfie:
 *                  type: string
 *                  description: 简介
 *                  required: true
 *                more_meta:
 *                  type: string
 *                  description: 更多信息
 *                keywords:
 *                  type: string
 *                  description: 关键字
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/addBlogTiltleBrfie", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.titleAndBrfie_add);
    if (data.code > 200) {
        return res.json(data)
    }
    data = data.data;
    if (data.is_show == 1) {
        let showSql = createSqlv2().update("blog_title_brfie").set({ is_show: 0 }).where(`is_show = 1`).build();
        await Db.query(showSql, res);
    }
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = createSqlv2().insert("blog_title_brfie").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataBlogTiltleBrfie:
 *    post:
 *      tags:
 *      - 后台管理 博客标题和简介
 *      summary: 博客标题和简介-修改
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                brfie:
 *                  type: string
 *                  description: 简介
 *                  required: true
 *                more_meta:
 *                  type: string
 *                  description: 更多信息
 *                keywords:
 *                  type: string
 *                  description: 关键字
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataBlogTiltleBrfie", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID, is_show } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.titleAndBrfie_add);
        if (data.code > 200) {
            return res.json(data)
        }
        data = data.data;
    } else {
        data = { is_show: is_show }
    }
    if (data.is_show == 1) {
        let showSql = createSqlv2().update("blog_title_brfie").set({ is_show: 0 }).where(`is_show = 1`).build();
        await Db.query(showSql, res);
    }
    data.updatetime = utils.getTime();
    let sql = createSqlv2().update("blog_title_brfie").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delBlogTiltleBrfie:
 *    post:
 *      tags:
 *      - 后台管理 博客标题和简介
 *      summary: 博客标题和简介-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/delBlogTiltleBrfie", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    data = {
        updatetime: utils.getTime(),
        is_del: 1
    }
    sql = createSqlv2().update("blog_title_brfie").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getTopImg:
 *    get:
 *      tags:
 *      - 后台管理 顶部图管理
 *      summary: 顶部图管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: top_img_name
 *          description: 图片名称
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getTopImg", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, top_img_name } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;

    let sql = createSqlv2().select('top_img.* , user_admin.user_name as createByUser')
        .from("top_img")
        .leftJoin("user_admin")
        .on(`user_admin.ID = top_img.createByUser`)
        .where(`top_img.is_del != 1`)
        .and(top_img_name ? ` top_img.top_img_name LIKE '%${top_img_name}%' ` : '')
        .order("top_img.addtime DESC")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select('count(*) as count').from("top_img").where(`top_img.is_del != 1`).and(top_img_name ? ` top_img.top_img_name LIKE '%${top_img_name}%' ` : '').end();
    let result = await Db.query(sql, res);
    let count = await Db.query(conutSql, res);
    if (result.code || count.code) return;
    result = utils.formatDateByArray(result, ['addtime', 'updatetime']);
    result = utils.deleteArrayObject(result, ['is_del']);
    result.forEach(item => {
        item.image_url = config.httpImgUrl + item.image_url;
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: count[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addTopImg:
 *    post:
 *      tags:
 *      - 后台管理 顶部图管理
 *      summary:  顶部图管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                top_img_name:
 *                  type: string
 *                  description: 图片名称
 *                  required: true
 *                image_url:
 *                  type: string
 *                  description: 图片地址
 *                  required: true
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addTopImg", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.top_img_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    let sql = "";
    let result = null;
    // 只能显示一张
    if (data.is_show == 1) {
        sql = createSqlv2().update("top_img").set({ is_show: 0, updatetime: utils.getTime() }).where(`is_del != 1`).end();
        result = await Db.query(sql, res);
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    sql = createSqlv2().insert("top_img").value(data).end();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
        data: {
            ID: data.ID
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/updateTopImg:
 *    post:
 *      tags:
 *      - 后台管理 顶部图管理
 *      summary:  顶部图管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                top_img_name:
 *                  type: string
 *                  description: 图片名称
 *                  required: true
 *                image_url:
 *                  type: string
 *                  description: 图片地址
 *                  required: true
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateTopImg", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = isLogin.data;
    if (data.top_img_name) {
        data = utils.checkData(req.body, objectCheck.top_img_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = "";
    let result = null;
    if (data.is_show == 1) {
        sql = createSqlv2().update("top_img").set({ is_show: 0, updatetime: utils.getTime() }).where(`is_del != 1`).end();
        result = await Db.query(sql, res);
    }
    if (data.image_url) {
        data.image_url = data.image_url.replace(config.httpImgUrl, "");
    }
    data.updatetime = utils.getTime();
    sql = createSqlv2().update("top_img").set(data).where(`ID = '${data.ID}'`).end();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delTopImg:
 *    post:
 *      tags:
 *      - 后台管理 顶部图管理
 *      summary: 顶部图管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delTopImg", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("top_img").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).end();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getNav:
 *    get:
 *      tags:
 *      - 后台管理 web端菜单管理
 *      summary: web端菜单管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: title
 *          description: 名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: isParent
 *          description: 是否只要父级
 *          in: query
 *          required: false
 *          type: boolean
 *        - name: isAdd
 *          description: 添加文章的
 *          in: query
 *          required: false
 *          type: boolean
 *        - name: isAll
 *          description: 添加文章的
 *          in: query
 *          required: false
 *          type: boolean
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getNav", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, isParent, isAdd, isAll } = req.query;
    let sql = '';
    /**只有父级*/
    if (isParent == 'true') {
        sql = createSqlv2().select().from("web_menu").where(`is_del != 1`).and(`(pid = '' or pid is null)`).order("sorts DESC").build();
        let result = await Db.query(sql, res);
        if (result.code) return;
        result = utils.deleteArrayObject(result, ["is_del"]);
        result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
        return res.json({
            code: 200,
            data: {
                data: result
            }
        })
    }

    /**可添加文章*/
    if (isAdd == 'true') {
        sql = createSqlv2().select().from("web_menu").where(`is_del != 1`).and(`is_article != 1`).order("sorts").build()
        let result = await Db.query(sql, res);
        if (result.code) return;
        result = utils.deleteArrayObject(result, ["is_del"]);
        result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
        return res.json({
            code: 200,
            data: {
                data: result
            }
        })
    }

    /**全部*/
    if (isAll == 'true') {
        sql = createSqlv2().select('web_menu.* , user_admin.user_name as createByUser')
            .from("web_menu")
            .leftJoin("user_admin")
            .on(`user_admin.ID = web_menu.createByUser`)
            .where(`web_menu.is_del != 1`)
            .and(title ? `web_menu.title like '%${title}%'` : '')
            .order("web_menu.sorts").build();
        let result = await Db.query(sql, res);
        if (result.code) return;
        result = utils.deleteArrayObject(result, ["is_del"]);
        result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
        return res.json({
            code: 200,
            data: {
                data: result
            }
        })
    }

    sql = createSqlv2().select('web_menu.* , user_admin.user_name as createByUser')
        .from("web_menu")
        .leftJoin("user_admin")
        .on(`user_admin.ID = web_menu.createByUser`)
        .where(`web_menu.is_del != 1`)
        .and(title ? `web_menu.title like '%${title}%'` : '')
        .order("sorts").build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    result = utils.deleteArrayObject(result, ["is_del"]);
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result.forEach(item => {
        item.icon = item.icon ? config.httpImgUrl + item.icon : null;
    })
    let list = result.filter(item => !item.pid);
    list.forEach(item => {
        item.children = result.filter(children => children.pid == item.ID);
    })
    return res.json({
        code: 200,
        data: {
            data: list,
            count: 0
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addNav:
 *    post:
 *      tags:
 *      - 后台管理 web端菜单管理
 *      summary:  web端菜单管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                pid:
 *                  type: string
 *                  description: 父级ID
 *                icon:
 *                  type: number
 *                  description: 图标
 *                path:
 *                  type: number
 *                  description: 跳转地址
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addNav", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.nav_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = createSqlv2().insert("web_menu").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataNav:
 *    post:
 *      tags:
 *      - 后台管理 web端菜单管理
 *      summary:  web端菜单管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                pid:
 *                  type: string
 *                  description: 父级ID
 *                icon:
 *                  type: number
 *                  description: 图标
 *                path:
 *                  type: number
 *                  description: 跳转地址
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataNav", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.nav_add);
        if (data.code > 200) return res.json(data)
        data = data.data;
    } else {
        data = req.body;
    }
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().update("web_menu").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delNav:
 *    post:
 *      tags:
 *      - 后台管理 web端菜单管理
 *      summary: web端菜单管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delNav", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("web_menu").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getLinks:
 *    get:
 *      tags:
 *      - 后台管理 友情链接
 *      summary: 友情链接-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 标题
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getLinks", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('friendly_links.* , user_admin.user_name as createByUser')
        .from('friendly_links')
        .leftJoin("user_admin")
        .on(`user_admin.ID = friendly_links.createByUser`)
        .where(`friendly_links.is_del = 0`)
        .and(title ? `friendly_links.title like '%${title}%'` : "")
        .order("friendly_links.addtime DESC")
        .limit(`${pageSize * (page - 1)} , ${pageSize}`).build();
    let countSql = createSqlv2().select("count(*) as count")
        .from("friendly_links").where(`friendly_links.is_del = 0`)
        .and(title ? `friendly_links.title like '%${title}%'` : "").build();
    let result = await Db.query(sql, res);
    let countReslt = await Db.query(countSql, res);
    if (result.code || countReslt.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countReslt[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addLinks:
 *    post:
 *      tags:
 *      - 后台管理 友情链接
 *      summary: 友情链接-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                url:
 *                  type: string
 *                  description: 链接地址
 *                  required: true
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/addLinks", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.links_add);
    if (data.code > 200) return res.json(data)
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = createSqlv2().insert("friendly_links").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataLinks:
 *    post:
 *      tags:
 *      - 后台管理 友情链接
 *      summary: 友情链接-修改
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                url:
 *                  type: string
 *                  description: 链接地址
 *                  required: true
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataLinks", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID, is_show } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.links_add);
        if (data.code > 200) return res.json(data)
        data = data.data;
    } else {
        data = { is_show: is_show }
    }
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().update("friendly_links").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delLinks:
 *    post:
 *      tags:
 *      - 后台管理 友情链接
 *      summary: 友情链接-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delLinks", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    data = {
        updatetime: utils.getTime(),
        createByUser: isLogin.data.ID,
        is_del: 1
    }
    sql = createSqlv2().update("friendly_links").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getSearch:
 *    get:
 *      tags:
 *      - 后台管理 搜索管理
 *      summary: 搜索管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 标题
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getSearch", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('search_settings.* , user_admin.user_name as createByUser')
        .from("search_settings")
        .leftJoin("user_admin")
        .on(`user_admin.ID = search_settings.createByUser`)
        .where(`search_settings.is_del = 0`)
        .and(title ? `search_settings.title like '%${title}%'` : "")
        .order("addtime DESC").limit(`${pageSize * (page - 1)} , ${pageSize}`).build();
    let countSql = createSqlv2().select("count(*) as count")
        .from("search_settings")
        .where(`is_del = 0`)
        .and(title ? `title like '%${title}%'` : "").build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addSearch:
 *    post:
 *      tags:
 *      - 后台管理 搜索管理
 *      summary: 搜索管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                url:
 *                  type: string
 *                  description: 链接地址
 *                  required: true
 *                is_stop:
 *                  type: number
 *                  description: 是否停用
 *                is_activity:
 *                  type: number
 *                  description: 是否活动
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addSearch", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.search_add);
    if (data.code > 200) return res.json(data)
    data = data.data;
    let sql = createSqlv2().select().from("search_settings").where(`title = '${data.title}' AND is_del != 1`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    if (result.length) {
        return res.json({
            ...errorCode[10002],
            message: '关键词已存在'
        })
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    sql = createSqlv2().insert("search_settings").value(data).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataSearch:
 *    post:
 *      tags:
 *      - 后台管理 搜索管理
 *      summary: 搜索管理-修改
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                url:
 *                  type: string
 *                  description: 链接地址
 *                  required: true
 *                is_stop:
 *                  type: number
 *                  description: 是否停用
 *                is_activity:
 *                  type: number
 *                  description: 是否活动
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataSearch", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.search_add);
        if (data.code > 200) return res.json(data)
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = createSqlv2().select().from("search_settings")
        .where(` is_del != 1`)
        .and(`ID != '${ID}'`)
        .and(`title = '${data.title}'`)
        .build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    if (result.length) {
        return res.json({
            ...errorCode[10002],
            message: '关键词已存在'
        })
    }
    delete data.ID;
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    sql = createSqlv2().update("search_settings").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delSearch:
 *    post:
 *      tags:
 *      - 后台管理 搜索管理
 *      summary: 搜索管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delSearch", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("search_settings").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getProtocol:
 *    get:
 *      tags:
 *      - 后台管理 协议管理
 *      summary: 协议管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 协议名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: type
 *          description: 协议类型
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getProtocol", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title, type } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('protocol.* , user_admin.user_name as createByUser')
        .from("protocol")
        .leftJoin("user_admin")
        .on(`user_admin.ID = protocol.createByUser`)
        .where(` protocol.is_del != 1`)
        .and(title ? `protocol.title LIKE '%${title}%'` : '')
        .and(type ? `type = '${type}'` : '')
        .order("addtime DESC")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`)
        .build();
    let conutSql = createSqlv2().select('count(*) as count')
        .from("protocol")
        .where(` is_del != 1`)
        .and(title ? `title LIKE '%${title}%'` : '')
        .and(type ? `type = '${type}'` : '')
        .end();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(conutSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ['addtime', 'updatetime']);
    result = utils.deleteArrayObject(result, ['is_del']);
    result.forEach(item => {
        item.content = item.content ? decodeURIComponent(item.content) : null;
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addProtocol:
 *    post:
 *      tags:
 *      - 后台管理 协议管理
 *      summary:  协议管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 协议名称
 *                  required: true
 *                type:
 *                  type: string
 *                  description: 协议类型
 *                  required: true
 *                content:
 *                  type: string
 *                  description: 协议内容
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addProtocol", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.protocol_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.content = encodeURIComponent(data.content) || "";
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().insert("protocol").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/updateProtocol:
 *    post:
 *      tags:
 *      - 后台管理 协议管理
 *      summary:  协议管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 协议名称
 *                type:
 *                  type: string
 *                  description: 协议类型
 *                content:
 *                  type: string
 *                  description: 协议内容
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateProtocol", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    }
    catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID, title } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.protocol_add);
        data = data.data;
        if (data.code > 200) return res.json(data)
        data.content = data.content ? encodeURIComponent(data.content) : "";
    } else {
        data.is_show = req.body.is_show;
    }
    if (data.code > 200) return res.json(data);
    data.updatetime = utils.getTime();
    delete data.ID;
    let sql = createSqlv2().update("protocol").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delProtocol:
 *    post:
 *      tags:
 *      - 后台管理 协议管理
 *      summary: 协议管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delProtocol", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("protocol").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getSelfEvaluation:
 *    get:
 *      tags:
 *      - 后台管理 自我评价
 *      summary: 自我评价-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: content
 *          description: 文章内容
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getSelfEvaluation", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, content } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('my_evaluation.* , user_admin.user_name as createByUser')
        .from("my_evaluation")
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_evaluation.createByUser`)
        .where(`my_evaluation.is_del != 1`)
        .and(content ? `my_evaluation.content LIKE '%${content}%'` : '')
        .order("my_evaluation.addtime DESC").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let countSql = createSqlv2().select('count(*) as count').from("my_evaluation").where(`is_del != 1`)
        .and(content ? `content LIKE '%${content}%'` : '').build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        },
    })
})

/**
 * @swagger
 * /api/v2/admin/addSelfEvaluation:
 *    post:
 *      tags:
 *      - 后台管理 自我评价
 *      summary:  自我评价-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                content:
 *                  type: string
 *                  description: 内容
 *                  required: true
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addSelfEvaluation", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.SelfEvaluation_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = "";
    if (data.is_show == 1) {
        sql = createSqlv2().update("my_evaluation").set({ is_show: 0 }).where(`is_show = 1`).build();
        let result = await Db.query(sql, res);
        if (result.code) return;
    }
    sql = createSqlv2().insert("my_evaluation").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})


/**
 * @swagger
 * /api/v2/admin/updateSelfEvaluation:
 *    post:
 *      tags:
 *      - 后台管理 自我评价
 *      summary:  自我评价-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                content:
 *                  type: string
 *                  description: 内容
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateSelfEvaluation", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = {};
    const { ID, content } = req.body;
    if (!ID) return res.json(errorCode[10003])
    if (content) {
        data = utils.checkData(req.body, objectCheck.SelfEvaluation_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = "";
    if (data.is_show == 1) {
        sql = createSqlv2().update("my_evaluation").set({ is_show: 0 }).where(`is_show = 1`).build();
        let result = await Db.query(sql, res);
        if (result.code) return;
    }
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    sql = createSqlv2().update("my_evaluation").set(data).where(`ID = '${ID}'`).end();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delSelfEvaluation:
 *    post:
 *      tags:
 *      - 后台管理 自我评价
 *      summary: 自我评价-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 文章ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delSelfEvaluation", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().select().from("my_evaluation").where(`ID = '${ID}'`).build();
    let select = await Db.query(sql, res);
    if (select.code < 0) return;
    sql = createSqlv2().update("my_evaluation").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getAbility:
 *    get:
 *      tags:
 *      - 后台管理 我的能力
 *      summary: 我的能力-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: ability
 *          description: 能力
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getAbility", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, ability } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('my_abilitys.* , user_admin.user_name as createByUser')
        .from("my_abilitys")
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_abilitys.createByUser`)
        .where('my_abilitys.is_del = 0')
        .and(ability ? `my_abilitys.ability LIKE '%${ability}%'` : '')
        .order("my_abilitys.sorts").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let countSql = createSqlv2().select('count(*) as count').from("my_abilitys")
        .where('is_del = 0').and(ability ? `ability LIKE '%${ability}%'` : '').build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ['addtime', 'updatetime']);
    result = utils.deleteArrayObject(result, ['is_del']);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        },
    })
})

/**
 * @swagger
 * /api/v2/admin/addAbility:
 *    post:
 *      tags:
 *      - 后台管理 我的能力
 *      summary:  我的能力-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ability:
 *                  type: string
 *                  description: 能力
 *                  required: true
 *                sort:
 *                  type: Number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/addAbility", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.Ability_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    if (!data.sorts) {
        data.sorts = 99;
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().insert("my_abilitys").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/updateAbility:
 *    post:
 *      tags:
 *      - 后台管理 我的能力
 *      summary:  我的能力-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                ability:
 *                  type: string
 *                  description: 能力
 *                sort:
 *                  type: Number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateAbility", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    let { ID, ability } = req.body;
    if (!ID) return res.json(errorCode[10003])
    if (isLogin.code > 200) return;
    let data = {};
    if (!ability) {
        data = utils.checkData(req.body, objectCheck.Ability_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
    } else {
        data = req.body;
    }
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    delete data.ID;
    let sql = createSqlv2().update("my_abilitys").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delAbility:
 *    post:
 *      tags:
 *      - 后台管理 我的能力
 *      summary: 我的能力-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 能力ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delAbility", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    if (isLogin.code > 200) return;
    let sql = createSqlv2().update("my_abilitys").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/exportAbility:
 *    post:
 *      tags:
 *      - 后台管理 我的能力
 *      summary: 我的能力-导出
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/exportAbility", async (req, res) => {
    let sql = createSqlv2().select().from("my_abilitys").where(`is_del != 1`).order("sorts").build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    let conf = {
        cols: [],
        rows: []
    };
    result.forEach(v => {
        v.addtime = utils.getTime(v.addtime);
        v.updateTime = v.updateTime ? utils.getTime(v.updateTime) : "";
        delete v.is_show;
        let arr = [v.ID, v.ability, v.sorts, v.updateTime, v.addtime];
        conf.rows.push(arr);
    })
    conf.cols = [
        { caption: 'ID', type: 'string' },
        { caption: '能力', type: 'string' },
        { caption: '排序', type: 'number' },
        { caption: '更新时间', type: 'string' },
        { caption: '添加时间', type: 'string' },
    ]
    let data = nodeExcel.execute(conf);
    res.setHeader('Content-Type', 'application/vnd.openxmlformats');
    res.setHeader("Content-Disposition", "attachment; filename=" + `myAbility-${new Date().getTime()}.xlsx`);
    res.end(data, 'binary');
})

/**
 * @swagger
 * /api/v2/admin/getSchool:
 *    get:
 *      tags:
 *      - 后台管理 学校管理
 *      summary: 学校管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: school
 *          description: 学校名称
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getSchool", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, school } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('my_school.* , user_admin.user_name as createByUser')
        .from('my_school')
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_school.createByUser`)
        .where(`my_school.is_del != 1`)
        .and(school ? `my_school.school LIKE '%${school}%'` : '')
        .order("my_school.sorts")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select('count(*) as count').from("my_school").where(`is_del != 1`).and(school ? `school LIKE '%${school}%'` : '').build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(conutSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ['addtime', 'updatetime']);
    result = utils.deleteArrayObject(result, ['is_del']);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        },
    })
})

/**
 * @swagger
 * /api/v2/admin/addSchool:
 *    post:
 *      tags:
 *      - 后台管理 学校管理
 *      summary:  学校管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                times:
 *                  type: string
 *                  description: 就读年限
 *                  required: true
 *                school:
 *                  type: string
 *                  description: 学校名称
 *                  required: true
 *                major:
 *                  type: string
 *                  description: 专业名称
 *                  required: true
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addSchool", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.school_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    if (!data.sorts) {
        data.sorts = 99;
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().insert("my_school").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/updateSchool:
 *    post:
 *      tags:
 *      - 后台管理 学校管理
 *      summary:  学校管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                 type: string
 *                 description: ID
 *                 required: true
 *                times:
 *                  type: string
 *                  description: 就读年限
 *                school:
 *                  type: string
 *                  description: 学校名称
 *                major:
 *                  type: string
 *                  description: 专业名称
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateSchool", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID, school } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (school) {
        data = utils.checkData(req.body, objectCheck.school_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
    } else {
        data = req.body;
    }
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    delete data.ID;
    let sql = createSqlv2().update("my_school").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delSchool:
 *    post:
 *      tags:
 *      - 后台管理 学校管理
 *      summary: 学校管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delSchool", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("my_school").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getMyProject:
 *    get:
 *      tags:
 *      - 后台管理 项目经历
 *      summary: 项目经历-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 标题
 *          in: query
 *          required: false
 *          type: string
 *        - name: introduce
 *          description: 项目介绍
 *          in: query
 *          required: false
 *          type: string
 *        - name: duty
 *          description: 负责内容
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getMyProject", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title, introduce, duty } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('my_project.* , user_admin.user_name as createByUser')
        .from("my_project")
        .leftJoin("user_admin")
        .on(`user_admin.ID = my_project.createByUser`)
        .where(`my_project.is_del != 1`)
        .and(title ? ` my_project.title LIKE '%${title}%' ` : "")
        .and(introduce ? ` my_project.introduce LIKE '%${introduce}%' ` : "")
        .and(duty ? ` my_project.duty LIKE '%${duty}%' ` : "")
        .order("my_project.sorts DESC").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select('count(*) as count').from("my_project")
        .where(`is_del != 1`)
        .and(title ? ` title LIKE '%${title}%' ` : "")
        .and(introduce ? ` introduce LIKE '%${introduce}%' ` : "").build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(conutSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addMyProject:
 *    post:
 *      tags:
 *      - 后台管理 项目经历
 *      summary:  项目经历-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                time:
 *                  type: string
 *                  description: 项目时间
 *                  required: true
 *                introduce:
 *                  type: string
 *                  description: 项目介绍
 *                  required: true
 *                duty:
 *                  type: string
 *                  description: 职责 / 负责内容
 *                  required: true
 *                technology:
 *                  type: string
 *                  description: 技术栈
 *                  required: true
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addMyProject", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.myProject_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    if (!data.sorts) {
        data.sorts = 99;
    }
    data.ID = utils.getUuid();
    data.addtime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    let sql = createSqlv2().insert("my_project").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200],
    })
})

/**
 * @swagger
 * /api/v2/admin/updateMyProject:
 *    post:
 *      tags:
 *      - 后台管理 项目经历
 *      summary:  项目经历-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                time:
 *                  type: string
 *                  description: 项目时间
 *                introduce:
 *                  type: string
 *                  description: 项目介绍
 *                duty:
 *                  type: string
 *                  description: 职责 / 负责内容
 *                technology:
 *                  type: string
 *                  description: 技术栈
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateMyProject", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID, title } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.myProject_add);
        if (data.code > 200) return res.json(data);
        data = data.data;
    } else {
        data = req.body;
    }
    data.createByUser = isLogin.data.ID;
    data.updatetime = utils.getTime();
    let sql = createSqlv2().update("my_project").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delMyProject:
 *    post:
 *      tags:
 *      - 后台管理 项目经历
 *      summary: 项目经历-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 学校ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delMyProject", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("my_project").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getArticle:
 *    get:
 *      tags:
 *      - 后台管理 文章管理
 *      summary: 文章管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 文章标题
 *          in: query
 *          required: false
 *          type: string
 *        - name: content
 *          description: 文章内容
 *          in: query
 *          required: false
 *          type: string
 *        - name: type
 *          description: 文章类型 ID
 *          in: query
 *          required: false
 *          type: string
 *        - name: isAll
 *          description: 查询所有文章
 *          in: query
 *          required: false
 *          type: Boolean
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getArticle", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title, type, brfie, isAll } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = "";
    if (isAll == 'true') {
        sql = createSqlv2().select().from('article_view').where(`is_del != 1`).order("addtime DESC").build();
        let result = await Db.query(sql, res);
        if (result.code) return;
        return res.json({
            data: {
                data: result,
                count: result.length
            },
            ...successCode[200]
        })
    }
    sql = createSqlv2().select().from('article_view')
        .where(`is_del != 1`)
        .and(title ? ` title LIKE '%${title}%' ` : "")
        .and(brfie ? ` brfie LIKE '%${brfie}%' ` : "")
        .and(type ? ` typeID = '${type}' ` : "")
        .order("addtime DESC").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select('count(*) as count').from('article_view')
        .where(`is_del != 1`)
        .and(title ? ` title LIKE '%${title}%' ` : "")
        .and(brfie ? ` brfie LIKE '%${brfie}%' ` : "")
        .and(type ? ` typeID = '${type}' ` : "").build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(conutSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    result.forEach(item => {
        item.imgUrl = item.imgUrl ? config.httpImgUrl + item.imgUrl : null;
    });
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/getArticleById:
 *    get:
 *      tags:
 *      - 后台管理 文章管理
 *      summary: 文章管理-根据ID查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          description: ID
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getArticleById", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.query;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().select('my_article.* , web_menu.title AS typeName')
        .from('my_article')
        .leftJoin("web_menu")
        .on("my_article.typeID = web_menu.ID")
        .where(`my_article.ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    let data = result[0];
    data.imgUrl = data.imgUrl ? config.httpImgUrl + data.imgUrl : null;
    data.content = data.content ? decodeURIComponent(data.content) : null;
    return res.json({
        ...successCode[200],
        data: {
            data: data
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addArticle:
 *    post:
 *      tags:
 *      - 后台管理 文章管理
 *      summary:  文章管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                reading:
 *                  type: string
 *                  description: 阅读量
 *                  required: true
 *                typeID:
 *                  type: string
 *                  description: 类型ID
 *                  required: true
 *                keywords:
 *                  type: string
 *                  description: 关键字
 *                imgUrl:
 *                  type: string
 *                  description: 图片地址
 *                brfie:
 *                  type: string
 *                  description: 简介
 *                content:
 *                  type: string
 *                  description: 内容
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addArticle", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.article_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    data.content = encodeURIComponent(data.content);
    let sql = createSqlv2().insert("my_article").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataArticle:
 *    post:
 *      tags:
 *      - 后台管理 文章管理
 *      summary:  文章管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 文章ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                reading:
 *                  type: string
 *                  description: 阅读量
 *                typeID:
 *                  type: string
 *                  description: 类型ID
 *                imgUrl:
 *                  type: string
 *                  description: 图片地址
 *                brfie:
 *                  type: string
 *                  description: 简介
 *                content:
 *                  type: string
 *                  description: 内容
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *                
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataArticle", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.article_add);
        if (data.code > 200) {
            return res.json(data)
        }
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = "";
    data.imgUrl = data.imgUrl ? data.imgUrl.replace(config.httpImgUrl, "") : "";
    if (data.imgUrl) {
        let imgUrlArr = data.imgUrl.split("/");
        let pathArr = imgUrlArr.filter(item => { return item == "https:" || item == "http:" });
        let imgUrl = data.ImgUrl;
        if (!pathArr.length) {
            imgUrl = "";
        }
        if (imgUrl) {
            sql = createSqlv2().select().from("my_article").where(`ID = '${ID}'`).build();
            let select = await Db.query(sql, res);
            if (select.length && data.imgUrl != select[0].imgUrl) {
                if (select.code < 0) return;
                if (select[0].imgUrl) {
                    let delFile = path.resolve(__dirname, '../upload/' + select[0].imgUrl);
                    utils.deleteFile({
                        filePath: delFile
                    })
                }
            }
        }
    }
    delete data.ID;
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    data.content = data.content ? encodeURIComponent(data.content) : "";
    if (!data.content) delete data.content;
    sql = createSqlv2().update("my_article").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delArticle:
 *    post:
 *      tags:
 *      - 后台管理 文章管理
 *      summary: 文章管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 文章ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delArticle", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().update("my_article").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getBanner:
 *    get:
 *      tags:
 *      - 后台管理 轮播图管理
 *      summary: 轮播图管理-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 轮播图名称
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getBanner", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('banner.* , user_admin.user_name as createByUser , my_article.title as articleTitle')
        .from("banner")
        .leftJoin("user_admin ON user_admin.ID = banner.createByUser")
        .leftJoin("my_article ON my_article.ID = banner.articleID")
        .where(`banner.is_del != 1`)
        .and(title ? `banner.title like '%${title}%'` : "")
        .order('banner.addtime DESC')
        .limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let countSql = createSqlv2().select("count(*) as count")
        .from("banner")
        .where(`is_del != 1`)
        .and(title ? `title like '%${title}%'` : "").build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    result.forEach(v => {
        v.path = v.path ? decodeURIComponent(v.path) : '';
        v.mpPath = v.mpPath ? decodeURIComponent(v.mpPath) : '';
        v.ImgUrl = v.ImgUrl ? config.httpImgUrl + v.ImgUrl : ''
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/addBanner:
 *    post:
 *      tags:
 *      - 后台管理 轮播图管理
 *      summary: 轮播图管理-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                ImgUrl:
 *                  type: string
 *                  description: 图片地址
 *                articleID:
 *                  type: string
 *                  description: 关联文章ID
 *                mpPath:
 *                  type: number
 *                  description: 小程序地址
 *                path:
 *                  type: number
 *                  description: 跳转地址
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_text:
 *                  type: number
 *                  description: 是否显示文字
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */

router.post("/addBanner", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.banner_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    data.mpPath = data.mpPath ? encodeURIComponent(data.mpPath) : null;
    data.path = data.path ? encodeURIComponent(data.path) : null;
    let sql = createSqlv2().insert("banner").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updataBanner:
 *    post:
 *      tags:
 *      - 后台管理 轮播图管理
 *      summary: 轮播图管理-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                articleID:
 *                  type: string
 *                  description: 文章ID
 *                ImgUrl:
 *                  type: string
 *                  description: 图片地址
 *                mpPath:
 *                  type: number
 *                  description: 小程序地址
 *                path:
 *                  type: number
 *                  description: 跳转地址
 *                sorts:
 *                  type: number
 *                  description: 排序
 *                is_text:
 *                  type: number
 *                  description: 是否显示文字
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataBanner", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.banner_add);
        if (data.code > 200) return res.json(data)
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = "";
    data.ImgUrl = data.ImgUrl ? data.ImgUrl.replace(config.httpImgUrl, '') : null;
    if (data.ImgUrl) {
        sql = createSqlv2().select().from("banner").where(`ID = '${ID}'`).build();
        let select = await Db.query(sql, res);
        if (data.ImgUrl != select[0].ImgUrl) {
            if (select.code < 0) return;
            if (select[0].ImgUrl) {
                let delFile = path.resolve(__dirname, '../upload/' + select[0].ImgUrl);
                utils.deleteFile({
                    filePath: delFile
                })
            }
        }
    }
    delete data.ID;
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    data.mpPath = data.mpPath ? encodeURIComponent(data.mpPath) : null;
    data.path = data.path ? encodeURIComponent(data.path) : null;
    sql = createSqlv2().update("banner").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delBanner:
 *    post:
 *      tags:
 *      - 后台管理 轮播图管理
 *      summary: 轮播图管理-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delBanner", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("banner").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getCommit:
 *    get:
 *      tags:
 *      - 后台管理 留言数据
 *      summary: 留言数据-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: content
 *          description: 内容
 *          in: query
 *          required: false
 *          type: string
 *        - name: article
 *          description: 文章名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: username
 *          description: 用户名
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getCommit", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, content, article, username } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select()
        .from("article_comment_view")
        .where(`is_del != 1`)
        .and(content ? `content LIKE '%${content}%'` : "")
        .and(article ? `articleTitle LIKE '%${article}%'` : "")
        .and(username ? `createByUser LIKE '%${username}%'` : "")
        .and("(reply_id IS NULL OR reply_id = '')")
        .limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let countSql = createSqlv2().select("count(*) as count")
        .from("article_comment_view")
        .where(`is_del != 1`)
        .and("(reply_id IS NULL OR reply_id = '')")
        .and(content ? `content LIKE '%${content}%'` : "")
        .and(article ? `articleTitle LIKE '%${article}%'` : "")
        .and(username ? `createByUser LIKE '%${username}%'` : "")
        .build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(countSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    result.forEach(item => {
        item.hasChildren = true;
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})


/**
 * @swagger
 * /api/v2/admin/getCommitById:
 *    get:
 *      tags:
 *      - 后台管理 留言数据
 *      summary: 留言数据-根据ID查询回复列表
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: ID
 *          default: 10
 *          description: ID
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getCommitById", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.query;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().select()
        .from("article_comment_view")
        .where(`is_del != 1`)
        .and(`reply_id = '${ID}'`)
        .order("addtime desc")
        .build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"])
    return res.json({
        ...successCode[200],
        data: {
            data: result
        }
    })
})

/**
 * @swagger
 * /api/v2/admin/updateCommit:
 *    post:
 *      tags:
 *      - 后台管理 留言数据
 *      summary: 留言数据-加精 顶置 是否显示
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                is_refining:
 *                  type: string
 *                  description: 加精
 *                is_top:
 *                  type: string
 *                  description: 顶置
 *                is_show:
 *                  type: number
 *                  description: 是否显示
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateCommit", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { is_refining, is_top, is_show, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    is_refining != undefined ? data.is_refining = is_refining : null;
    is_top != undefined ? data.is_top = is_top : null;
    is_show != undefined ? data.is_show = is_show : null;
    data.updatetime = utils.getTime();
    let sql = createSqlv2().update("article_comment").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delCommit:
 *    post:
 *      tags:
 *      - 后台管理 留言数据
 *      summary: 留言数据-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delCommit", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let sql = createSqlv2().update("article_comment").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/getVisits:
 *    get:
 *      tags:
 *      - 后台管理 首页接口
 *      summary: 首页接口-访问量
 *      produces:
 *      - application/json
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getVisits", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    }
    catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let sql = "";
    sql = createSqlv2().select().from("admin_index_visits").build();
    let result = [];
    result = await Db.query(sql, res);
    if (result.code) return;
    let sendData = {};
    result.forEach(item => {
        sendData[item.province] = item.count;
    })
    res.json({
        ...successCode[200],
        data: sendData
    })
    sql = createSqlv2().select('iplocation.province,COUNT(*) AS count')
        .from('actionlog')
        .join('iplocation')
        .on('actionlog.ip = iplocation.ip')
        .group('iplocation.province')
        .order('count', 'desc')
        .build();
    result = await Db.query(sql, res);
    if (result.code) return;
    let insertData = [];
    result.forEach(item => {
        insertData.push({
            province: item.province,
            count: item.count,
            createTime: utils.getTime(),
            ID: utils.getUuid()
        });
    })
    // 清空 admin_index_visits
    sql = createSqlv2().customAll("delete from admin_index_visits").build();
    result = await Db.query(sql, res);
    sql = createSqlv2().insert('admin_index_visits').values(insertData).build();
    result = await Db.query(sql, res);
})


/**
 * @swagger
 * /api/v2/admin/getUserTask:
 *    get:
 *      tags:
 *      - 后台管理 用户任务
 *      summary: 用户任务-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 任务名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: is_finish
 *          description: 是否完成
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getUserTask", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { pageSize, page, title, is_finish } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;

    let sql = createSqlv2().select('user_task.* , admin_user.user_name as createByUser , GROUP_CONCAT(personnel_user.user_name) AS personnelList')
        .from('user_task')
        .leftJoin("user_admin AS admin_user ON admin_user.ID = user_task.createByUser")
        .leftJoin("user_admin AS personnel_user")
        .on(`FIND_IN_SET(personnel_user.ID, user_task.personnel)`)
        .where(`user_task.is_del != 1`)
        .and(title ? ` user_task.title LIKE '%${title}%' ` : "")
        .and(is_finish ? ` user_task.is_finish = '${is_finish}' ` : "")
        .group('user_task.ID')
        .order("addtime DESC").limit(`${pageSize * (page - 1)}, ${pageSize}`).build();
    let conutSql = createSqlv2().select('count(*) as count').from('user_task')
        .where(`is_del != 1`)
        .and(title ? ` title LIKE '%${title}%' ` : "")
        .and(is_finish ? ` is_finish = '${is_finish}' ` : "").build();
    let result = await Db.query(sql, res);
    let countResult = await Db.query(conutSql, res);
    if (result.code || countResult.code) return;
    result = utils.formatDateByArray(result, ["addtime", "updatetime"]);
    result = utils.deleteArrayObject(result, ["is_del"]);
    result.forEach(item => {
        item.personnel = item.personnel ? item.personnel.split(",") : [];
    })
    return res.json({
        ...successCode[200],
        data: {
            data: result,
            count: countResult[0].count
        }
    })
})


/**
 * @swagger
 * /api/v2/admin/addUserTask:
 *    post:
 *      tags:
 *      - 后台管理 用户任务
 *      summary: 用户任务-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                execution_time:
 *                  type: string
 *                  description: 执行时间
 *                personnel:
 *                  type: string
 *                  description: 参与人
 *                is_finish:
 *                  type: number
 *                  description: 是否完成
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addUserTask", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.user_task_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.createByUser = isLogin.data.ID;
    data.addtime = utils.getTime();
    data.ID = utils.getUuid();
    if (data.execution_time && new Date(utils.getTime()).getTime() < new Date(data.execution_time).getTime()) {
        schedule.openScheduleJob({
            id: data.ID,
            rule: data.execution_time,
            fn: () => {
                let sql = createSqlv2().update("user_task").set({
                    is_finish: 1,
                    updatetime: utils.getTime()
                }).where(`ID = '${data.ID}'`).build();
                Db.query(sql, res);
            }
        })
    }
    let sql = createSqlv2().insert("user_task").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/updataUserTask:
 *    post:
 *      tags:
 *      - 后台管理 用户任务
 *      summary: 用户任务-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                execution_time:
 *                  type: string
 *                  description: 执行时间
 *                personnel:
 *                  type: string
 *                  description: 参与人
 *                is_finish:
 *                  type: number
 *                  description: 是否完成
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updataUserTask", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { title, ID } = req.body;
    if (!ID) return res.json(errorCode[10003])
    let data = {};
    if (title) {
        data = utils.checkData(req.body, objectCheck.user_task_add);
        if (data.code > 200) {
            return res.json(data)
        }
        data = data.data;
    } else {
        data = req.body;
    }
    let sql = "";
    delete data.ID;
    data.updatetime = utils.getTime();
    data.createByUser = isLogin.data.ID;
    if (data.execution_time && new Date(utils.getTime()).getTime() < new Date(data.execution_time).getTime()) {
        schedule.openScheduleJob({
            id: data.ID,
            rule: data.execution_time,
            fn: () => {
                let sql = createSqlv2().update("user_task").set({
                    is_finish: 1,
                    updatetime: utils.getTime()
                }).where(`ID = '${data.ID}'`).build();
                Db.query(sql, res);
            }
        })
    }
    sql = createSqlv2().update("user_task").set(data).where(`ID = '${ID}'`).build();
    result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/delUserTask:
 *    post:
 *      tags:
 *      - 后台管理 用户任务
 *      summary: 用户任务-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/delUserTask", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().update("user_task").set({ is_del: 1, updatetime: utils.getTime() }).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})


/**
 * @swagger
 * /api/v2/admin/getMyAsset:
 *    get:
 *      tags:
 *      - 后台管理 我的资产
 *      summary: 我的资产-列表查询
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: pageSize
 *          default: 10
 *          description: 条数
 *          in: query
 *          required: false
 *          type: string
 *        - name: page
 *          default: 1
 *          description: 页码
 *          in: query
 *          required: false
 *          type: string
 *        - name: title
 *          description: 任务名称
 *          in: query
 *          required: false
 *          type: string
 *        - name: buy_amount
 *          description: 购买金额
 *          in: query
 *          required: false
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/getMyAsset", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let { pageSize, page, buy_amount } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('my_asset.* , user_admin.user_name as username').from("my_asset")
        .leftJoin("user_admin")
        .on('my_asset.create_user = user_admin.ID')
        .where('my_asset.is_del = 0')
        .and(buy_amount ? 'my_asset.buy_amount = ' + buy_amount : '')
        .limit(`${pageSize * (page - 1)}, ${pageSize}`)
        .order("my_asset.createdtime", "desc")
        .build();
    let countSql = createSqlv2().select("count(*) as count").from("my_asset")
        .where('my_asset.is_del = 0')
        .and(buy_amount ? 'my_asset.buy_amount = ' + buy_amount : '')
        .build();
    let data = await Db.query(sql, res);
    if (data.code) return;
    data = utils.formatDateByArray(data, ["createdtime", "updatetime" , 'buy_time']);
    data = utils.deleteArrayObject(data, ["is_del"]);
    // 计算每天的价格
    data.forEach(item => {
        item.day_count = Math.ceil((new Date().getTime() - new Date(item.buy_time).getTime()) / (24 * 60 * 60 * 1000));
        item.day_price = (item.buy_amount / item.day_count).toFixed(2);
        // 计算一下还差多少是10元每天
        let break_even_price = 10;
        let day = Number((item.buy_amount / break_even_price).toFixed(2));
        item.day_count_10 = day - item.day_count;
        // 预计回本日期
        item.back_time = utils.formatDate( 'yyyy-MM-dd' , new Date(new Date().getTime() + item.day_count_10 * 24 * 60 * 60 * 1000));
        // 是否回本呢
        item.is_back = item.day_price <= break_even_price;
        if (item.is_back) {
            item.tips = `已于${item.back_time}回本`
        } else {
            item.tips = `预计在${item.day_count_10}天后回本(${item.back_time})`
        }
        item.backTips = `在每天${break_even_price}元的情况下计算`
    });
    let countData = await Db.query(countSql);
    if (countData.code) return;
    return res.json({
        ...successCode[200],
        data: {
            data: data,
            count: countData[0].count
        }
    })
})


/**
 * @swagger
 * /api/v2/admin/addMyAsset:
 *    post:
 *      tags:
 *      - 后台管理 我的资产
 *      summary: 我的资产-添加
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                icon:
 *                  type: string
 *                  description: 图标
 *                buy_amount:
 *                  type: string
 *                  description: 购买金额
 *                  required: true
 *                buy_time:
 *                  type: number
 *                  description: 购买时间
 *                  required: true
 *                remarks:
 *                  type: string
 *                  description: 备注
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/addMyAsset", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.MyAsset_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.createdtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = "";
    sql = createSqlv2().insert("my_asset").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})

/**
 * @swagger
 * /api/v2/admin/updateMyAsset:
 *    post:
 *      tags:
 *      - 后台管理 我的资产
 *      summary: 我的资产-更新
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: ID
 *                  required: true
 *                title:
 *                  type: string
 *                  description: 标题
 *                  required: true
 *                icon:
 *                  type: string
 *                  description: 图标
 *                buy_amount:
 *                  type: string
 *                  description: 购买金额
 *                  required: true
 *                buy_time:
 *                  type: number
 *                  description: 购买时间
 *                  required: true
 *                remarks:
 *                  type: string
 *                  description: 备注
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/updateMyAsset", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let data = {};
    let sql = "";
    data = utils.checkData(req.body, objectCheck.MyAsset_add);
    if (data.code > 200) return res.json(data)
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.updatetime = utils.getTime();
    sql = createSqlv2().update("my_asset").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});

/**
 * @swagger
 * /api/v2/admin/deleteMyAsset:
 *    post:
 *      tags:
 *      - 后台管理 我的资产
 *      summary: 我的资产-删除
 *      produces:
 *      - application/json
 *      requestBody:
 *        description: Optional description in *Markdown*
 *        required: true
 *        content:
 *          application/json:
 *            schema:
 *              type: object
 *              properties:
 *                ID:
 *                  type: string
 *                  description: 用户ID
 *      responses:
 *        200:
 *          description: 返回结果
 * */
router.post("/deleteMyAsset", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSqlv2().select().from("my_asset").where(`ID = '${ID}'`).build();
    let data = await Db.query(sql, res);
    if (data.code) return;
    if (!data.length) {
        return res.json({
            ...errorCode[10008],
            message: "没有找到该数据"
        })
    }
    data = {
        updatetime: utils.getTime(),
        create_user: isLogin.data.ID,
        is_del: 1
    }
    sql = createSqlv2().update("my_asset").set(data).where(`ID = '${ID}'`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})




module.exports = router;